package gbench.appdemo.priceline.indicator;

import static gbench.common.tree.LittleTree.IRecord.REC;

import java.time.LocalDateTime;

import gbench.common.tree.LittleTree.IRecord;

/**
 * 
 * @author gbench
 *
 */
public class OhlcIndicatorEvaluator implements IIndicatorEvaluator<OHLC> {
    @Override
    public IRecord evaluate(final IRecord rec,final IRecord previous) {
        final var price = rec.dbl("price");// 最新价格信息
        final var volume = rec.lng("volume",0l);//最新的量能数据．
        final var time = rec.ldt("time");// K线时间,pricetime
        final var index = rec.lng("index");// 提取index
        if(previous==null) {// 初次创建
            return REC(  
                "index",index, // 索引坐标
                "time",time,// 更新时间
                "open",price, "high",price, "low",price, "close",price, 
                "volume",volume, "volume0",volume // 初始成交量
            );// REC
        }else {
            final IRecord r = previous.duplicate();// 在上次结果的基础上进行增量处理
            final var prev_time = previous.ldt("time");// 上次记录的更新时间
            r.compute("time",(v) -> IRecord.obj2target(v, LocalDateTime.class).isBefore(time) ? time:v);// 更新数据时间
            r.compute("high", (Double v) -> v<=price ? price : v);
            r.compute("low", (Double v) -> v>=price ? price : v);
            r.compute("close", (Double v)-> !prev_time.isAfter(time) ? price : v);
            //r.compute("open", (Double v)-> !prev_time.isAfter(time) ? v : price); // 修改开盘时间: 注释是因为重复数据发送的时候会导致收盘与开盘价格一样
            r.compute("volume", (Long v)-> !prev_time.isAfter(time) ? volume : v);
            return r;
        } // if
    }

    @Override
    public OHLC getIndicator(final IRecord rec) {
        return new OHLC(rec);
    }
}
